package com.carson.data.zuul.filter;

import com.carson.data.zuul.Result;
import com.carson.data.zuul.config.DataFilterConfig;
import com.carson.data.zuul.util.JwtUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component
public class PreAuthFilter extends ZuulFilter {
    private static Logger log = LoggerFactory.getLogger(PreAuthFilter.class);
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private DataFilterConfig dataFilterConfig;
    @Autowired
    private JwtUtil jwtUtil;

    private List<String> jwtKeys = Arrays.asList(Claims.AUDIENCE, Claims.EXPIRATION, Claims.ID,
            Claims.ISSUED_AT, Claims.ISSUER, Claims.NOT_BEFORE, Claims.SUBJECT);

    /**
     * pre：路由之前
     * routing：路由之时
     * post： 路由之后
     * error：发送错误调用
     *
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * filterOrder：过滤的顺序
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * shouldFilter：这里可以写逻辑判断，是否要过滤，本文true,永远过滤
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        // 获取到request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        if (!dataFilterConfig.getAuthExcludeUri().contains(request.getRequestURI())) {
            return true;
        }
        return false;
    }

    @Override
    public Object run() {

        // 获取到request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getHeader("token");
        Claims claims;
        try {
            claims = jwtUtil.parseJWT(token);
        } catch (Exception ex) {
            ex.printStackTrace();
            ctx.setSendZuulResponse(false); //不对其进行路由
            ctx.setResponseStatusCode(401);
            Result result = new Result();
            result.setCode(-1);
            result.setMessage("invalid token");
            try {
                ctx.setResponseBody(objectMapper.writeValueAsString(result));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            ctx.set("isSuccess", false);
            return null;
        }
        ctx.setSendZuulResponse(true); //对请求进行路由
        for (Map.Entry<String, Object> entry : claims.entrySet()) {
            String key = entry.getKey();
            if (!jwtKeys.contains(key)) {
                ctx.addZuulRequestHeader("yc-" + key, entry.getValue().toString());
            }
        }
        ctx.set("isSuccess", true);
        return null;
    }
}
